import sys
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtCore import QThread, pyqtSignal, QObject
from time import sleep
import threading
from PyQt5.QtNetwork import QTcpSocket, QTcpServer, QHostAddress

class TCP_Server_Qthread_function(QObject):
    
    signal_TCP_Server_qthread_function_Init = pyqtSignal()
    signal_pushButton_Open           = pyqtSignal(object)
    signal_pushButton_Open_flag      = pyqtSignal(object)
    signal_readyRead                 = pyqtSignal(object)
    signal_NewClient                 = pyqtSignal(object)
    signal_closeClient               = pyqtSignal(object)
    signal_send_data                 = pyqtSignal(object)
    signal_send_data_num             = pyqtSignal(object)
    
    def __init__(self, parent=None):
        super(TCP_Server_Qthread_function, self).__init__(parent)
        #开始调用网络信号
        self.state = 0 #0 未打开 1 打开 2 关闭
        self.listClient = []
        self.NewClient = []
        self.NewClient.insert(0,'ALL (' + str(len(self.listClient)) + ')')

    def slot_closeClient(self,parameter):
        ip_port = parameter.split(':', 1)
        if parameter.find('ALL') >= 0:
            for i  in range(len(self.listClient)):
                self.listClient[i].disconnected.disconnect(self.updatestate)
                self.listClient[i].readyRead.disconnect(self.slot_readyRead)
                self.listClient[i].close()
            self.NewClient.clear()
            self.listClient.clear()
            self.NewClient.insert(0,'ALL (' + str(len(self.listClient)) + ') connections')
            for i in range(len(self.listClient)):
                    self.NewClient.append(self.listClient[i].peerAddress().toString() + ":" + str(self.listClient[i].peerPort()))
            self.signal_NewClient.emit(self.NewClient)
        else:
            for i  in range(len(self.listClient)):
                ip = self.listClient[i].peerAddress().toString()
                port = self.listClient[i].peerPort()
                ip_port = ip + ":" + str(port)
                if parameter == ip_port:
                    self.listClient[i].disconnected.disconnect(self.updatestate)
                    self.listClient[i].readyRead.disconnect(self.slot_readyRead)
                    self.listClient[i].close()
                    del self.listClient[i]
                    self.NewClient.clear()
                    self.NewClient.insert(0,'ALL (' + str(len(self.listClient)) + ') connections')
                    for i in range(len(self.listClient)):
                            self.NewClient.append(self.listClient[i].peerAddress().toString() + ":" + str(self.listClient[i].peerPort()))
                    self.signal_NewClient.emit(self.NewClient)
                    return

    def slot_pushButton_Open(self,parameter):
        print("打开TCP Server", parameter)
        if self.state == 0:
            if self.tcpserver.listen(QHostAddress(parameter['ip']), int(parameter['port'])):
                self.state = 1
                self.signal_pushButton_Open_flag.emit(1)
            else:
                self.signal_pushButton_Open_flag.emit(0)
            self.signal_NewClient.emit(self.NewClient)
        else:
            for i  in range(len(self.listClient)):
                self.listClient[i].disconnected.disconnect(self.updatestate)
                self.listClient[i].readyRead.disconnect(self.slot_readyRead)
                self.listClient[i].close()
            self.listClient.clear()
            self.tcpserver.close()
            self.state = 0
            self.signal_pushButton_Open_flag.emit(2)

            self.NewClient.clear()
            self.NewClient.insert(0,'ALL (' + str(len(self.listClient)) + ')')
            self.signal_NewClient.emit(self.NewClient)
        
    def slot_readyRead(self):
        for i in range(len(self.listClient)):
            if self.listClient[i].bytesAvailable() > 0:
                buf = bytes()
                buf = self.listClient[i].readAll()
                data = {}
                data['ip']   = self.listClient[i].peerAddress().toString()
                data['port'] = self.listClient[i].peerPort()
                data['buf']  = buf
                self.signal_readyRead.emit(data)
                # print("TCP Server收到数据", data['ip'], data['port'], data['buf'])

    def updatestate(self):
        print("更新listClient")
        for i in range(len(self.listClient)):
            if self.listClient[i].state() == 0:
                del self.listClient[i]
                break

    def slot_send_data(self,parameter):
        print("TCP Server 发送数据", parameter)
        if self.state != 1:
            return

        if parameter['ip_port'].find('ALL') >= 0:
            for i  in range(len(self.listClient)):
                print("全部发送")
                self.listClient[i].write(parameter['data'])
                self.signal_send_data_num.emit(len(parameter['data']))
        else:
            for i  in range(len(self.listClient)):
                ip = self.listClient[i].peerAddress().toString()
                port = self.listClient[i].peerPort()
                ip_port = ip + ":" + str(port)
                if parameter['ip_port'] == ip_port:
                    self.listClient[i].write(parameter['data'])
                    self.signal_send_data_num.emit(len(parameter['data']))
                    return

    def newConnection(self):
        tcpClient = self.tcpserver.nextPendingConnection()
        print("新建连接",tcpClient.peerAddress().toString(),tcpClient.peerPort())
        tcpClient.readyRead.connect(self.slot_readyRead)
        tcpClient.disconnected.connect(self.updatestate)
        self.listClient.append(tcpClient)
        tcpClient.bytesAvailable()
        
        # del self.NewClient[0]
        # self.NewClient.insert(0,'ALL (' + str(len(self.listClient)) + ') connections')
        # self.NewClient.append(tcpClient.peerAddress().toString() + ":" + str(tcpClient.peerPort()))
        # self.signal_NewClient.emit(self.NewClient)
        
        self.NewClient.clear()
        self.NewClient.insert(0,'ALL (' + str(len(self.listClient)) + ') connections')
        for i in range(len(self.listClient)):
                self.NewClient.append(self.listClient[i].peerAddress().toString() + ":" + str(self.listClient[i].peerPort()))
        self.signal_NewClient.emit(self.NewClient)
        
    def TCP_Server_qthread_function_Init(self):
        self.tcpserver = QTcpServer()
        self.tcpserver.newConnection.connect(self.newConnection)